15. Loops
Loops
ND079 C1 L0 A14a Loops Intro
In Java there are three different types of loops:
while
loopsfor
loopsdo while
loops
while
Loop
ND079 C1 L0 A14b While Loop
The while
loop continuously executes as long as a given condition is True
. The syntax looks like this
while(condition){
Execution block
}
Here's a concrete example:
int i = 0;
while(i < 5){
System.out.println(i);
i++;
}
Notice that we first set a counter variable, i
, to keep track of how many times the loop has run. Each time it runs, we increment this variable by 1 (that's what i++
is doing). While i
is less than 5
, we continue to iterate, printing out the value of i
every time.
for
loop
Next, let's look at the for loop. Here's what the general syntax looks like:
ND079 C1 L0 A14c For Loop
for(initialization; condition; increment or decrement){
Execution block
}
And here's a concrete example:
for(int i = 0; i < 5; i++){
System.out.println(i);
}
do while
Loop
ND079 C1 L0 A14d Do While Loop
Finally, here is the syntax for the do while
loop:
do {
Execution block
} while(condition);
And here's a concrete example:
int i = 0;
do {
System.out.println(i);
i++;
} while(i < 5);
The do while
loop is very similar to the while
loop. The key distinction is that the do while
loop runs the loop once first before it checks the condition. This means that even if the condition is false right from the start, the code inside the loop will still get run once.